// pages/hotel_details/hotel_details.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    more: true,
    // 酒店详情
    hotelDetails: null,
    // 评价
    score: '4.5',
    level: '超棒',
    // 弹窗内容
    showSheet: false, // 控制弹窗显示隐藏
    // 各筛选条件选中值（数组存选中的 name）
    selectedService: [], 
    selectedBreakfast: [],
    selectedRoomType: [],
    selectedPrice: [],
    // 时间选择器
    ruzhuDate:"",
    likaiDate:"",
    show: false,
    tianshu:"",
    start1:"",
    end1:"",
    // 地址
    jingdu:"",
    weidu:"",
    dizhi:"",
    mingcheng:"",
    // 房间列表
    roomList: [
      {
        image: "/images/room1.jpg",
        name: "大床房",
        desc: "无早餐 20-22㎡ 大床 2人入住 有窗",
        policy: "15分钟内可免费取消",
        comment: "套餐非常实惠",
        price: 158,
        originalPrice: 299
      },
      {
        image: "/images/room2.jpg",
        name: "双床房",
        desc: "无早餐 20-22㎡ 大床 2人入住 有窗",
        policy: "15分钟内可免费取消",
        comment: "套餐非常实惠",
        price: 158,
        originalPrice: 299
      },
      // 可继续添加更多房型数据
      {
        image: "/images/room3.jpg",
        name: "豪华单人房",
        desc: "无早餐 20-22㎡ 大床 2人入住 有窗",
        policy: "15分钟内可免费取消",
        comment: "套餐非常实惠",
        price: 158,
        originalPrice: 299
      }
    ],
    tagList: [
      "前台给力 100%",
      "周边遍历 100%",
      "干净卫生 98%",
      "房间好 98%",
      "设备不错 97%",
      "早餐不错 90%"
    ],
    reviewList: [
    ],
    tabs:[],
    prices: [[0,150], [150,300], [300,450], [450,600],[1000]],
    // 自定义图标
    price: null,
    radio: null,
    flag: true
  },
  // 单选框 -- 房间类型
  onChange(event) {
    console.log(event.detail);
    if(event.detail == this.data.radio){
      this.setData({
        flag: true,
        radio: null,
      })
      this.getRoomTypes2(this.data.hotelDetails.managerId, 1, 3, this.data.radio, this.data.price)
    }else{
      this.setData({
        flag: false,
        radio: event.detail,
      }); 
      this.getRoomTypes2(this.data.hotelDetails.managerId, 1, 5, this.data.radio, this.data.price)
    }
  },
  tosheshi(){
    wx.navigateTo({
      url: '/pages/hotel_equipment/hotel_equipment',
    })
  },
  // 单选框 -- 价格
  onChange2(event) {
    console.log(event.detail);
    if(event.detail == this.data.price){
      this.setData({
        flag: true,
        price: null,
      })
      this.getRoomTypes2(this.data.hotelDetails.managerId, 1, 3, this.data.radio, this.data.price)
    }else{
      this.setData({
        flag: false,
        price: event.detail,
      }); 
      this.getRoomTypes2(this.data.hotelDetails.managerId, 1, 5, this.data.radio, this.data.price)
    }
  },
  // 页面跳转
  toRoomDetails(e){
    app.globalData.roomInfo = e.currentTarget.dataset.room;
    app.globalData.startDate = this.data.start1;
    app.globalData.endDate = this.data.end1;
    app.globalData.tianShu = this.data.tianshu;
    console.log(this.data.start1);
    if(this.data.ruzhuDate != "" && this.data.likaiDate != ""){
      wx.navigateTo({
        url: '/pages/room_details/room_details',
      })
    }else {
      this.onDisplay()
    }
  },
  toPingJia(){
    wx.navigateTo({
      url: '/pages/hotel_pingjia/hotel_pingjia',
    })
  },
  // 弹窗
   // 打开筛选弹窗
   openFilterSheet() {
    this.setData({ showSheet: true });
  },
  // 关闭弹窗
  closeSheet() {
    this.setData({ showSheet: false });
  },
  // 预定服务筛选 change 事件
  onServiceChange(e) {
    this.setData({ selectedService: e.detail });
  },
  // 早餐筛选 change 事件
  onBreakfastChange(e) {
    this.setData({ selectedBreakfast: e.detail });
  },
  // 房型筛选 change 事件
  onRoomTypeChange(e) {
    this.setData({ selectedRoomType: e.detail });
  },
  // 价格筛选 change 事件
  onPriceChange(e) {
    this.setData({ selectedPrice: e.detail });
  },
  // 重置筛选条件
  resetFilter() {
    this.setData({
      selectedService: [],
      selectedBreakfast: [],
      selectedRoomType: [],
      selectedPrice: []
    });
  },
  // 确认筛选（可在此处理筛选逻辑，如请求接口等）
  confirmFilter() {
    const { 
      selectedService, 
      selectedBreakfast, 
      selectedRoomType, 
      selectedPrice 
    } = this.data;
    console.log('选中的预定服务：', selectedService);
    console.log('选中的早餐：', selectedBreakfast);
    console.log('选中的房型：', selectedRoomType);
    console.log('选中的价格：', selectedPrice);
    // 可根据筛选条件发起请求，更新页面数据
    this.closeSheet(); // 关闭弹窗
  },
  // 时间
  onDisplay() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getMonth() + 1}月${date.getDate()}日`;
  },
  onConfirm(event) {
    const [start, end] = event.detail;
    this.setData({
      start1: start,
      end1: end
    })
    let start1 = new Date(start);
    let end1 = new Date(end);
    this.setData({
      show: false,
      date: `${this.formatDate(start)} - ${this.formatDate(end)}`,
      ruzhuDate: this.formatDate(start),
      likaiDate: this.formatDate(end),
      tianshu: end1.getDate() - start1.getDate()
    });
    console.log(this.data);
  },
  // 地址检查权限
  checkLocationAuth() {
    wx.getSetting({
      success: (res) => {
        if (res.authSetting['scope.userLocation']) {
          // 已授权，直接获取位置
          this.getLocation();
        } else if (res.authSetting['scope.userLocation'] === undefined) {
          // 未授权过，主动请求授权
          wx.authorize({
            scope: 'scope.userLocation',
            success: () => this.getLocation(),
            fail: () => {
              // 授权被拒，引导去设置页
              wx.showModal({
                title: '需要位置权限',
                content: '请在设置中开启位置权限',
                success: (modalRes) => {
                  if (modalRes.confirm) wx.openSetting();
                }
              });
            }
          });
        } else {
          // 已拒绝过，提示去设置页手动开
          wx.showModal({
            title: '权限被拒',
            content: '需手动开启位置权限',
            success: (modalRes) => {
              if (modalRes.confirm) wx.openSetting();
            }
          });
        }
      }
    });
  },
  getLocation(){
    const that = this;
    wx.getLocation({
      type: 'gcj02',
      success (res) {
        console.log(res);
        that.setData({
          jingdu: res.longitude,
          weidu: res.latitude
        })
      }
     })
  },
  huoqudizhi(){
    console.log(this.data.jingdu);
    console.log(this.data.weidu);
    wx.openLocation({
      latitude: Number(this.data.weidu),
      longitude: Number(this.data.jingdu),
    })
  },
  goBack(){
    wx.navigateBack()
  },
  getRoomTypes(managerId, pageNum, pageSize){
    wx.request({
      url: 'http://localhost:8080/system/type/list',
      method: 'GET',
      header: { 
        'Authorization':  app.globalData.token,// 认证token
      },
      data: {
        managerId: managerId,
        pageNum: pageNum,
        pageSize: pageSize
      },
      success: (res) => {
        // console.log(res);
        this.setData({
          roomList: res.data.rows
        })
        console.log(this.data.roomList);
      }
    })
  },
  getRoomTypes2(managerId, pageNum, pageSize, roomTypeName, price){
    const params = {
      managerId,
      pageNum,
      pageSize,
      roomTypeName: roomTypeName
    };
    // 只添加有值的价格参数
  if (price) {
    if (price.length === 2) {
      const [min, max] = price;
      params.minPrice = min;
      params.maxPrice = max;
    } else if (price.length === 1) {
      params.minPrice = price[0];
    }
  }
    wx.request({
      url: 'http://localhost:8080/system/type/list',
      method: 'GET',
      header: { 
        'Authorization':  app.globalData.token,// 认证token
      },
      data: params,
      success: (res) => {
        console.log(res);
        this.setData({
          roomList: res.data.rows
        })
      }
    })
  },
  getabs(managerId){
    wx.request({
      url: 'http://localhost:8080/system/type/list',
      method: 'GET',
      header: { 
        'Authorization':  app.globalData.token,// 认证token
      },
      data: {
        managerId: managerId,
        pageNum: 1,
        pageSize: 100
      },
      success: (res) => {
        if (res.data && res.data.rows && res.data.rows.length > 0) {
          // 提取roomTypeName字段并存储到tabs数组中
          const tabs = res.data.rows.map(item => item.roomTypeName);
          this.setData({
            tabs: tabs
          });
        }
      },
    })
  },
  // 展示全部
  showMore(){
    this.getRoomTypes(this.data.hotelDetails.managerId, 1, 100);
    this.setData({
      more: false
    })
    this.getabs(this.data.hotelDetails.managerId)
  },
  // 收起
  showLess(){
    this.getRoomTypes(this.data.hotelDetails.managerId, 1, 3);
    this.setData({
      more: true
    })
  },
  getPingJiaList(){
    wx.request({
      url: 'http://localhost:8080/system/review/list',
      method: 'GET',
      header: { 
        'Authorization':  app.globalData.token,// 认证token
      },
      data: {
        userId: app.globalData.hotelInfo.managerId,
        hotelId: app.globalData.hotelInfo.hotelId,
        pageNum: 1,
        pageSize: 2
      },
      success: (res) => {
        console.log(res);
         // 转换时间格式
  const formattedList = res.data.rows.map(item => {
    // 处理 createTime
    if (item.createTime) {
      const datePart = item.createTime.split(' ')[0]; // 提取日期部分
      item.createTime = datePart.replace(/-/g, '/');  // 替换分隔符
    }
    // 处理图片
    if (item.imageUrls && typeof item.imageUrls === 'string') {
      // 按逗号分隔并过滤空值
      item.imageUrls = item.imageUrls.split(',')
        .map(url => url.trim())
        .filter(url => url.length > 0);
    } else {
      // 如果没有图片或格式错误，设为空数组
      item.imageUrls = [];
    }
    // 处理 replyTime（如果需要）
    if (item.replyTime) {
      const replyDate = new Date(item.replyTime);
      item.replyTime = `${replyDate.getFullYear()}/${(replyDate.getMonth() + 1).toString().padStart(2, '0')}/${replyDate.getDate().toString().padStart(2, '0')}`;
    }
    
    return item;
  });
        this.setData({
          reviewList: formattedList
        })
        console.log(this.data.reviewList);
      }
    })
  },
  onLoad(options) {
    this.setData({
        hotelDetails: app.globalData.hotelInfo
      })
      // 获取房型信息
      this.getRoomTypes(this.data.hotelDetails.managerId, 1, 3);
      this.getabs(this.data.hotelDetails.managerId);
      this.getPingJiaList();
  },

  onReady() {

  },

  onShow() {
    this.setData({
      hotelDetails: app.globalData.hotelInfo
    })
    // 获取房型信息
    this.getRoomTypes(this.data.hotelDetails.managerId, 1, 3);
    this.getabs(this.data.hotelDetails.managerId);
    this.getPingJiaList();
  },

  onHide() {

  },

  onUnload() {

  },

  onPullDownRefresh() {

  },

  onReachBottom() {

  },

  onShareAppMessage() {

  }
})